package at.ac.tuwien.dse.health.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hsqldb.Server;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.io.File;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Starts an embedded HSQLDB server instance.
 *
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
public class EmbeddedHsqlServer implements InitializingBean, DisposableBean {
	private static final Logger LOGGER = LogManager.getFormatterLogger(EmbeddedHsqlServer.class);
	Server server = new Server();
	String databaseName;
	File databasePath;
	boolean started;

	public EmbeddedHsqlServer(String databaseName, File databasePath) {
		this.databaseName = checkNotNull(databaseName, "'databaseName' must not be null");
		this.databasePath = checkNotNull(databasePath, "'databasePath' must not be null");
	}

	@Override
	public void afterPropertiesSet() {
		// If the server is already running, return silently
		if (server.getState() != 16) {
			LOGGER.info("HSQLDB server instance is already running.");
			return;
		}

		LOGGER.info("Starting HSQLDB server with database '%s' at '%s'", databaseName, databasePath.getAbsolutePath());
		server.setDatabaseName(0, databaseName);
		server.setDatabasePath(0, databasePath.getAbsolutePath());
		server.setSilent(true);
		server.start();
		started = server.getState() != 16;
		if (!started) {
			LOGGER.warn("Cannot start HSQLDB server. Perhaps there is another instance running.");
		}
	}

	@Override
	public void destroy() {
		if (started) {
			LOGGER.info("Shutting down HSQLDB server with database '%s'", databaseName);
			server.shutdown();
			started = false;
		}
	}
}
